<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Jquery {

var $externalJquery='http://multihogar.lessrisk.cl/js/jquery.js';//http://localhost/codeigniter/js/jquery.js
var $jqueryScript='';

var $jqDocumentReady=false; //whether to automatically output $(document).ready()stuff

var $externalScripts=array();
var $errors=array();

//php4 constructor points to php5 constructor
function Jquery(){
  $this->__constructor();
}
//php5 constructor
function __constructor(){

  //for php.net
  //in php4 http_build_query is not available, this is a handwritten version
  //php5 has such a function //is used for POST and GET stuff
  if (!function_exists('http_build_query')) {
		function http_build_query($data, $prefix='', $sep='', $key='') {
		   $ret = array();
		   foreach ((array)$data as $k => $v) {
		       if (is_int($k) && $prefix != null) $k = urlencode($prefix . $k);
		       if (!empty($key)) $k = $key.'['.urlencode($k).']';
		      
		       if (is_array($v) || is_object($v))
		           array_push($ret, http_build_query($v, '', $sep, $k));
		       else    array_push($ret, $k.'='.urlencode($v));
		   }
		
		   if (empty($sep)) $sep = ini_get('arg_separator.output');
		   return implode($sep, $ret);
		}
	}
}
//set the url of jquery.js //defaults to jquery.js but if you want to alter name/path 
function setExternalJquery($url){

  $this->externalJquery=$url;
}
//add external script like <script src='$url' type='text/javascript'>, loads into an array to be looped in the final jqeury process
function addExternalScript($url,$type='text/javascript'){
  $this->externalScripts[]='<script type="'.$type.'"  src="'.$url.'"></script>';
  return true;
}
//sets $this->jqueryScript
function setJqueryScript($script=''){

  $this->jqueryScript=$script;
  return true;

}
//appends $script to $this->jqueryScript
function addJqueryScript($script=''){

  $this->setJqueryScript($this->jqueryScript . $script);
  return true;  
}
//outputs the variable $this->jqueryScript (no <script> stuff, handy if you want to load some jquery via ajax)
function printJqueryScript(){
  echo $this->jqueryScript;
}
//If set to true $(document).ready(function(){ $this->jqueryScript }); will be outputted, instead of without the $(document).ready stuff //saves a line of code that is often used. Defaults to false
function setJqDocumentReady($int){
  $this->jqDocumentReady=$int;
  return true;
}
function mensaje_alerta($mensaje,$funcion_call){   
    $codigo_jquery='$("#alerta").modal({
		closeHTML: "<a href=\'#\'title=\'Close\' class=\'modal-close\'>x</a>",
		position: ["20%",],
		overlayId: "alerta-overlay",
		containerId: "alerta-container", 
		onShow: function (dialog) {
			var modal = this;

			$(".message", dialog.data[0]).append("'.$mensaje.'");

			// if the user clicks "yes"
			$(".yes", dialog.data[0]).click(function () {'.$funcion_call.'
				modal.close(); // or $.modal.close();
			});
		}
	});';
        return $codigo_jquery;  
}
function mensaje_cargando($funcion_call){
    $codigo_jquery='$("#loading").modal({
		closeHTML: "<a href=\'#\'title=\'Close\' class=\'modal-close\'>x</a>",
		position: ["20%",],
		overlayId: "loading-overlay",
		containerId: "loading-container", 
		onShow: function (dialog) {
			var modal = this;
			// if the user clicks "yes"
			$(".yes", dialog.data[0]).click(function () {'.$funcion_call.'
				modal.close(); // or $.modal.close();
			});
		}
	});';
        return $codigo_jquery;  
}
function mensaje_error($mensaje,$funcion_call){   
    $codigo_jquery='$("#error").modal({
		closeHTML: "<a href=\'#\'title=\'Close\' class=\'modal-close\'>x</a>",
		position: ["20%",],
		overlayId: "error-overlay",
		containerId: "error-container", 
		onShow: function (dialog) {
			var modal = this;

			$(".message", dialog.data[0]).append("'.$mensaje.'");

			// if the user clicks "yes"
			$(".yes", dialog.data[0]).click(function () {'.$funcion_call.'
				modal.close(); // or $.modal.close();
			});
		}
	});';
        return $codigo_jquery;  
}

function mensaje_confirmar($mensaje,$funcion_call){   
    $codigo_jquery='$("#confirm").modal({
		closeHTML: "<a href=\'#\'title=\'Close\' class=\'modal-close\'>x</a>",
		position: ["20%",],
		overlayId: "confirm-overlay",
		containerId: "confirm-container", 
		onShow: function (dialog) {
			var modal = this;

			$(".message", dialog.data[0]).append("'.$mensaje.'");

			// if the user clicks "yes"
			$(".yes", dialog.data[0]).click(function () {'.$funcion_call.'
				modal.close(); // or $.modal.close();
			});
		}
	});';
        return $codigo_jquery;  
}
function asignar_ajax($nombre_ajax,$controlador,$metodo,$variables){
        $this -> JqueryObject ( $nombre_ajax, 'ajax' );
        $this -> $nombre_ajax -> setbeforeSend($this->mensaje_cargando('')); 
        $this -> $nombre_ajax -> setRequestUrl (base_url().'index.php/'.$controlador.'/'.$metodo );
        $this -> $nombre_ajax -> setDataType ('script'); 
        $this -> $nombre_ajax -> setData ( $variables );  
        $this -> $nombre_ajax -> setRequestType ('POST');
        $this -> $nombre_ajax -> setSuccessFunction("$.modal.close();");
        return $this -> getJqueryObject ( $nombre_ajax );  
}

function show($nombre_objeto,$value,$retornar=false){
        $nombre_instancia="show_".$nombre_objeto;
        $this -> JqueryObject ($nombre_instancia, 'prop' );
        $this -> $nombre_instancia -> asignar_nombre_objeto("#".$nombre_objeto ); 
        $this -> $nombre_instancia -> asignar_propiedad ("show");
        $this ->$nombre_instancia -> asignar_value ( $value ); //bind it
        if ($retornar==false){
            $this -> addJqueryObject ($nombre_instancia); //back to original class
        } else{
            return $this ->getJqueryObject($nombre_instancia); //back to original class
        }
}

function hide($nombre_objeto,$value,$retornar=false){
        $nombre_instancia="hide_".$nombre_objeto;
        $this -> JqueryObject ($nombre_instancia, 'prop' );
        $this -> $nombre_instancia -> asignar_nombre_objeto("#".$nombre_objeto ); 
        $this -> $nombre_instancia -> asignar_propiedad ("hide");
        $this -> $nombre_instancia -> asignar_value ( $value ); //bind it
        if ($retornar==false){
            $this -> addJqueryObject ($nombre_instancia); //back to original class
        } else{
            return $this ->getJqueryObject($nombre_instancia); //back to original class
        }
}
function asignar_submit_formulario($nombre_formulario,$funcion_envio='',$funcion_recepcion='',$tipo='json',$devolver=false){
        $this -> JqueryObject ( $nombre_formulario, 'form' ); //new object of type event
        $this -> $nombre_formulario -> asignar_formulario ( "#".$nombre_formulario ); //attach to a.wronglink
        $this -> $nombre_formulario -> asignar_tipo ($tipo);
        $this -> $nombre_formulario -> asignar_function_envio ($funcion_envio);
        $this -> $nombre_formulario -> asignar_function_recepcion ( $funcion_recepcion ); //bind it
        if ($devolver){
            return $this ->getJqueryObject ($nombre_formulario );
        }else{
            $this -> addJqueryObject ( $nombre_formulario );
            return null;   
        } 
}
function asignar_evento($nombre_objeto_evento,$evento,$funcion){
    $this -> JqueryObject ( $nombre_objeto_evento , 'event' ); //new object of type event
        $this -> $nombre_objeto_evento -> assignEventTo ( "#".$nombre_objeto_evento ); //attach to a.wronglink
        $this -> $nombre_objeto_evento -> assignJavascript ("function(e){ ".$funcion."}");
        $this -> $nombre_objeto_evento -> assignType ( 'bind' ); //bind it
        $this -> $nombre_objeto_evento -> assignEvent ( $evento); //trigger event on click 
        $this -> addJqueryObject ( $nombre_objeto_evento );
}
function asignar_tributo($nombre_instancia,$atributo,$valor,$devolver){
        $this -> JqueryObject  ( $nombre_instancia ,  'assign' );
        if ($valor=="data.responseText"){
            $this -> $nombre_instancia -> assignValue ("'".$atributo."',".$valor.""); //value to be added
        }else{
            $this -> $nombre_instancia -> assignValue ("'".$atributo."','".$valor."'"); //value to be added
        }
        $this -> $nombre_instancia -> assignValueTo ( '#'.$nombre_instancia ); //value is added to all A in the DOM
        $this -> $nombre_instancia -> assignLocation ( 'attr' ); //value is added to href attribute
        if ($devolver){
            return $this ->getJqueryObject ($nombre_instancia );
        }else{
            $this -> addJqueryObject ( $nombre_instancia );
            return null;   
        } 
    }


function jQueryError($error, $description=false){
  $this->errors[]=$error . ' - '. $description;
  return true;
}
///outputs the entire Jquery Javascript stuff, including the externally loaded scripts.
function processJquery(){
  $result= '<script type="text/javascript"  src="'.$this->externalJquery.'"></script>';

  foreach($this->externalScripts as $externalScript){
    $result.=$externalScript;
  }
  if(!empty($this->errors)) {
    $result.='<script type="text/javascript">';
    $result.='$(document).ready(function(){';
    $errors='';
    foreach($this->errors as $error)
      $errors.=$error;
    $result.='alert("'.trim($errors).'")';
    $result.='});';
    $result.='</script>';
    return $result;
  }
  
  $result.='<script type="text/javascript">';
  //$this->jqueryScript 
  if($this->jqDocumentReady==true) $this->jqueryScript='$(document).ready(function(){'. $this->jqueryScript . '});';
  
  
  $result.=$this->jqueryScript;
  

  
  $result.='</script>';
  return $result;
}
	//outputs the script, include <script> stuff
  function printJquery(){
    echo $this->processJquery();
  }
  
	function JqueryObject($instanceName,$type){
	$type=strtolower($type);

  if($type=='ajax') $oName='JqueryAjax';
  elseif($type=='assign') $oName='JqueryAssign';
  elseif($type=='event') $oName='JqueryEvent';
  elseif($type=='form') $oName='JqueryForm';
  elseif($type=='prop') $oName='JqueryPropiedad';
  

  $this->$instanceName=new $oName();
  
  }
	function addJqueryObject($instanceName){
	  $result=$this->$instanceName->getJquery();
	  $this->addJqueryScript($result);
	}
	function getJqueryObject($instanceName){
	  $result=$this->$instanceName->getJquery();
	  return $result;//$this->getJqueryScript($result);
	}


}

class JqueryEvent{

  var $script;
  var $eventType='bind';
  var $value='ddddd';
  var $elementName;
  var $objectName;
  var $event='click';
  function JqueryEvent(){}

  function assignEventTo($elementName){
  $this->elementName=$elementName;
  }
  function assignJavascript($script){
  $this->script=$script;
  }
  function assignType($eventType){ //Bind, Unbind that list
    $this->eventType=$eventType;
  }
  function assignEvent($event){
    $this->event=$event;
  }
  function getJquery(){
   return '$("'.$this->elementName.'").'.$this->eventType.'("'.$this->event.'",'.$this->script.');';

  }
}
class JqueryPropiedad{
  var $script;
  var $propiedad='';
  var $value='';
  var $objectName;
  function JqueryPropiedad(){}

  function asignar_propiedad($propiedad){
    $this->propiedad=$propiedad;
  }
  function asignar_nombre_objeto($objectName){
    $this->objectName=$objectName;
  }
  function asignar_value($value){ //Bind, Unbind that list
    $this->value=$value;
  }
  function getJquery(){
   return '$("'.$this->objectName.'").'.$this->propiedad.'("'.$this->value.'");';

  }
}
class JqueryAjax{
var $ajaxTypes=array();
var $ajaxDataTypes=array();
var $ajaxbeforeSend=array();

var $requestType='POST';
var $datatype='html';
var $data=array();
var $url=false;
var $success_function=false;
var $errors=array();
function JqueryAjax(){

$this->__constructor();
}
function __constructor($dd='',$ss='',$sa=''){
  $this->ajaxTypes=array('POST','GET');
  $this->ajaxDataTypes=array('html','script','xml','json');
  $this->requestType='POST';
  


}



function jQueryAjaxError($error, $description=false){
  $this->errors[]=$error . ' - '. $description;
  print_r($this->errors);
  die();
}
function setDataType($datatype){

  $this->datatype=strtolower($datatype);
  if(!in_array($this->datatype,$this->ajaxDataTypes))  $this->jQueryAjaxError('Wrong datatype given','$datatype = '.$this->datatype);
}
function setRequestType($requestType){
  $this->requestType=strtoupper($requestType);
    if(!in_array($this->requestType,$this->ajaxTypes))  $this->jQueryAjaxError('Wrong type given','$type = '.$this->requestType);
}
function setbeforeSend($beforeSend){
    $this->ajaxbeforeSend=$beforeSend;
}
function setRequestUrl($url){
  $this->url=$url;
}
function setSuccessFunction($script){
$this->success_function=$script;
}
function setDataRaw($data){
$this->data=$data;

}
  function setData($data){
  
    if(!$this->data=http_build_query($data))  $this->jQueryAjaxError('Wrong data given','$data'.$this->data);
  }
  function getJquery(){
  $ajaxCall='$.ajax({';
  $ajaxCall.=' type: "'.$this->requestType .'"';
  $ajaxCall.=', url: "'.$this->url.'"';
  if ($this->ajaxbeforeSend){
        $ajaxCall.=', beforeSend: function(objeto){'.$this->ajaxbeforeSend.'}' ;
  }
  $ajaxCall.=', data: "'.$this->data.'"' ;
  $ajaxCall.=', dataType: "'.$this->datatype.'"' ;
  if($this->success_function!=false) $ajaxCall.=',success: function(data) {' .$this->success_function .'}';
   
  $ajaxCall.='});';
  
  return $ajaxCall;
  }


}

class JqueryAssign{
  var $script;
  var $location='after';
  var $value='ddddd';
  var $elementName;
  var $objectName;

  
  function JqueryAssign(){

  
  }
  function assignValueTo($elementName){
  $this->elementName=$elementName;
  }
  function assignValue($value){

  $this->value=$value;
  }
  function assignLocation($location){
  $this->location=$location;
  }
  function getJquery(){
  return '$("'.$this->elementName.'").'.$this->location.'('.$this->value.');';
  }
}
class JqueryForm{
  var $script;
  var $formulario='';
  var $function_envio='';
  var $tipo_respuesta;
  var $function_recepcion;
  var $objectName;
  
  function JqueryForm(){
  }
  function asignar_formulario($Nombre_formulario){
    $this->formulario=$Nombre_formulario;
  }
  function asignar_tipo($tipo){
        $this->tipo_respuesta=$tipo;
  }
  function asignar_function_envio($function){

  $this->function_envio=$function;
  }
  function asignar_function_recepcion($function){
  $this->function_recepcion=$function;
  }
  function getJquery(){

  $retorno="$('".$this->formulario."').submit(function() {
                $.ajax({
                    type: 'POST',
                    dataType: '".$this->tipo_respuesta."',
                    url: $('".$this->formulario."').attr('action'),
                    data: $('".$this->formulario."').serialize(),
                    error:function(objeto){
                       // alert('Disculpe las molestias a Ocurrido Un error En este Momento Estamos enviando Informacion del error a nuestros administradores');
                        alert('ERROR->'+objeto.responseText);
                        //$.ajax({
                        //    type: 'POST',
                        //    dataType: 'json',
                        //    url: '".base_url()."index.php/con_error/error',
                        //    data: {error: objeto.responseText} ,
                        //    error:function(objeto){
                        //        alert('ERROR->'+objeto.responseText);
                        //    }
                        //});
                        //window.location.href = '".base_url()."index.php/con_ingreso_consulta/index';
                    }";
                    if ($this->function_envio<>""){
                        $retorno.=",beforeSend: function(data) {".$this->function_envio."}";
                    } 
                    if ($this->function_recepcion<>""){
                        $retorno.=",success: function(data) {".$this->function_recepcion."}";
                    }                     
                $retorno.="})
                return false;
            });";
    return $retorno;
  }
}

?>